/*
 * Created on 2008-4-12
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.tongji.quickCRUDQ.webapp.handler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolver;
import org.springframework.web.servlet.mvc.multiaction.MethodNameResolver;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;

import com.tongji.quickCRUDQ.exception.FormatException;
import com.tongji.quickCRUDQ.model.CommonBean;
import com.tongji.quickCRUDQ.permit.ToolBar;
import com.tongji.quickCRUDQ.util.RequestUtil;

import edu.tongji.jiaowu.service.ParameterManager;
import edu.tongji.jiaowu.webapp.session.SessionParameter;
import edu.tongji.jiaowu.webapp.session.SessionParameterLocal;

/**
 * @author Administrator
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class QuickUrlHandler extends HandlerInterceptorAdapter implements ServletContextAware {
    private final Log log = LogFactory.getLog(this.getClass());
	private final Map urlMap = new HashMap();
	private ServletContext servletContext; 
	private ToolBar toolBar;
	private ParameterManager parameterManager;


	public void setMappings(Properties mappings) {
		this.urlMap.putAll(mappings);
	}

	public void setUrlMap(Map urlMap) {
		this.urlMap.putAll(urlMap);
	}
	
	
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object command){
		try {
//			CommonBean curShoolYear=parameterManager.findParameterByName("CURRENT_SHCOOL_YEAR");
//			CommonBean curShoolSemester=parameterManager.findParameterByName("CURRENT_SHCOOL_SEMESTER");
//			request.setAttribute("CURRENT_SHCOOL_YEAR", curShoolYear.getPropertyAsString(0,"value1"));
//			request.setAttribute("CURRENT_SHCOOL_SEMESTER", curShoolSemester.getPropertyAsString(0,"value1"));
			
	    	String pathInfo=(String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
			RequestUtil.processThreadLocalParameter(request);
			String handlerName = (String) this.urlMap.get(pathInfo);
			if(handlerName==null) return true;
			log.info("pathInfo:"+pathInfo+",handlerName:"+handlerName);
			QuickHandler handler=(QuickHandler)(WebApplicationContextUtils.getWebApplicationContext(this.servletContext).getBean(handlerName));
			if(handler!=null) handler.preHandle(request,response,command);
			return true;
		} catch (NoSuchRequestHandlingMethodException e) {
			e.printStackTrace();
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.context.ServletContextAware#setServletContext(javax.servlet.ServletContext)
	 */
	public void setServletContext(ServletContext arg0) {
		this.servletContext=arg0;
	}

	/* (non-Javadoc)
	 * @see com.tongji.quickCRUDQ.webapp.handler.QuickHandler#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
	 */
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object command, ModelAndView modelAndView) throws Exception {
		try {
	    	String pathInfo=(String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
	    	
	    	String tableName=request.getParameter("tableName");
	    	Map cookieMap=(Map) request.getAttribute("cookie");
	    	if(cookieMap!=null&&tableName==null) tableName=(String) cookieMap.get("tableName");
	    	
	        SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            boolean administrator = false;
            GrantedAuthority[] rolesa = auth.getAuthorities();
            List roles=new ArrayList();
            for (int i = 0; i < rolesa.length; i++) {
				roles.add(rolesa[i].toString());
			}
            String buttons="";
	    	if(tableName!=null){
	    		String quickGroup=request.getParameter("quickGroup");
	    		if(quickGroup!=null){
	    			buttons=toolBar.show(pathInfo, tableName,quickGroup, roles);
	    		}else{
	    			buttons=toolBar.show(pathInfo, tableName, roles);
	    		}
	    	}else{
	    		buttons=toolBar.show(pathInfo, roles);
	    	}
	    	request.setAttribute("buttons", buttons);
	    	
			String handlerName = (String) this.urlMap.get(pathInfo);
			if(handlerName==null) return ;
			log.info("pathInfo:"+pathInfo+",handlerName:"+handlerName);
			QuickHandler handler=(QuickHandler)(WebApplicationContextUtils.getWebApplicationContext(this.servletContext).getBean(handlerName));
			if(handler!=null) handler.postHandle(request,response,handler,modelAndView);
		} catch (NoSuchRequestHandlingMethodException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			SessionParameterLocal.setSessionParameter(null);
		}
		
	}

	/* (non-Javadoc)
	 * @see com.tongji.quickCRUDQ.webapp.handler.QuickHandler#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
	 */
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		// TODO Auto-generated method stub
		
	}

	public ToolBar getToolBar() {
		return toolBar;
	}

	public void setToolBar(ToolBar toolBar) {
		this.toolBar = toolBar;
	}

	public ParameterManager getParameterManager() {
		return parameterManager;
	}

	public void setParameterManager(ParameterManager parameterManager) {
		this.parameterManager = parameterManager;
	}
	

}
